package com.zm.demo.core.leetcode;

/**
 *
 *
 * [1,2,3,4,5,1, 23,34,5, 6,7,9]
 [3,4,5,1,2,21,2, 1, 5,12,5,1]
 * @author zoum
 * @create 2020/1/15 14:55
 */
public class CanCompleteCircuit {

    public int canCompleteCircuit(int[] gas, int[] cost) {
        int surplus = 0;
        int firstIndex = 0;
        for (int i=0, j=gas.length-1; i <= j; i++){
            surplus += (gas[i] - cost[i]);
            while (surplus < 0 && j>i){
                surplus += (gas[j] - cost[j]);
                firstIndex=j;
                j--;
            }
        }

        if (surplus  < 0){
            return -1;
        }else {
            return firstIndex;
        }
    }
}
